package com.dc.designPattern._1_singleton.impl.type5;


/**
 * Description: 懒汉式(线程安全，双重检查)
 * @author: gdc
 * @date: 2020/12/26
 * @version 1.0
 */
class Singleton {

	private Singleton() {}

	private static volatile Singleton INSTANCE;

	/**
	 * 提供一个静态的公有方法，加入双重检查代码，解决线程安全问题, 同时解决懒加载问题，同时保证了效率, 推荐使用
	 */
	public static Singleton getINSTANCE() {
		if(INSTANCE == null) {
			synchronized (Singleton.class) {
				if(INSTANCE == null) {
					INSTANCE = new Singleton();
				}
			}
		}
		return INSTANCE;
	}
}

public class SingletonTest05 {
	public static void main(String[] args) {
		System.out.println("双重检查");
		Singleton instance = Singleton.getINSTANCE();
		Singleton instance2 = Singleton.getINSTANCE();
		System.out.println(instance == instance2); // true
		System.out.println("INSTANCE.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}

}

